﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Xml;
using System.Xml.Serialization;

namespace KSS.Generator.Schema
{
    public class Type
    {
        private string _name;
        [XmlAttribute]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private string _id;
        [XmlAttribute]
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private List<Column> _columns;
        [XmlElement(ElementName = "Column", Type = typeof(Column))]
        public List<Column> Columns
        {
            get { return _columns; }
            set { _columns = value; }
        }

        private List<Association> _associations;
        [XmlElement(ElementName = "Association", Type = typeof(Association))]
        public List<Association> Associations
        {
            get { return _associations; }
            set { _associations = value; }
        }

        public Column GetColumn(string columnName)
        {
            return _columns.Find(
                delegate(Column c)
                {
                    return c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase);
                });
        }

        public List<Column> GetPrimaryColumns()
        {
            return _columns.FindAll(delegate(Column c)
                                    {
                                        return (c.IsPrimaryKey);
                                    });
        }

        public List<Column> GetForeignColumns()
        {
            List<Column> foreignColumns = new List<Column>();

            foreach (Association a in _associations)
            {
                if (a.IsForeignKey)
                {
                    foreignColumns.Add(GetColumn(a.ThisKey));
                }
            }

            return foreignColumns;
        }

        public List<Association> GetForeignAssociations()
        {
            return _associations.FindAll(
                delegate(Association a)
                {
                    return (a.IsForeignKey);
                });
        }
    }
}
